package com.yituo.mjworld.mvc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.mvc.dao.SearchConfDao;
import com.yituo.mjworld.mvc.entity.web.WebSearchConf;
import com.yituo.mjworld.core.web.core.BaseForm;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.service.BaseService;
import com.yituo.mjworld.core.web.core.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
public class SearchServiceImpl extends BaseService {


  @Autowired
  SearchConfDao searchConfDao;

  @Override
  public JSONObject getList(QueryForm form) {
    String countSql = "select count(id) from web_search_conf";
    String sql = "select id,title,url,orderNum from web_search_conf order by orderNum ";
    return this.get(sql, countSql, form, null);
  }

  @Override
  public Result delete(DeleteForm form) {
    Result result = new Result();
    WebSearchConf conf = (WebSearchConf) baseDao.get(WebSearchConf.class, form.getId());
    if (conf == null) {
      result.setResult(false).setMsg("欲删除的搜索配置文件不存在!");
    } else {
      baseDao.delete(WebSearchConf.class, form.getId());
      result.setResult(true);
    }
    return result;
  }

  @Override
  public Result saveOrUpdate(BaseForm baseForm) {
    Result result = new Result();
    WebSearchConf conf = (WebSearchConf) baseForm;
    WebSearchConf conf1 = (WebSearchConf) baseDao.get(WebSearchConf.class, conf.getId());
    WebSearchConf conf2 = searchConfDao.getSearchConfByTitle(conf.getTitle());
    if (conf1 == null) {
      // 新增操作
      if (conf2 == null) {
        // 不存在重复的标题
        baseDao.saveOrUpdate(conf);
        result.setResult(true);
      } else {
        result.setMsg("重复的标题").setResult(false);
      }
    } else {
      // update操作
      if (conf2 == null) {
        // 不存在重复标题
        baseDao.merge(conf);
        result.setResult(true);
      } else {
        // 存在重复的标题
        if (conf.getId() == conf2.getId()) {
          // 该重复标题的表项为自己本身
          baseDao.saveOrUpdate(conf);
          result.setResult(true);
        } else {
          result.setResult(false).setMsg("重复的标题");
        }
      }
    }
    return result;

  }

  /**
   * 统计加1
   *
   * @param id
   * @return
   */
  public Result clickCount(int id) {
    Result result = new Result();
    WebSearchConf obj = (WebSearchConf) this.baseDao.get(WebSearchConf.class, id);
    if (obj == null) {
      result.setResult(false).setMsg("您点击的热搜不存在!");
    } else {
      obj.setClickCount(obj.getClickCount() + 1);
      baseDao.saveOrUpdate(obj);
      result.setResult(true).setMsg("更新成功!");
    }
    return result;
  }
}
